package com.moyoutian.leetcode;

/**
 * 203. 移除链表元素
 * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点 。
 * <p>
 * <p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：head = [1,2,6,3,4,5,6], val = 6
 * 输出：[1,2,3,4,5]
 * <p>
 * 示例 2：
 * <p>
 * 输入：head = [], val = 1
 * 输出：[]
 * <p>
 * 示例 3：
 * <p>
 * 输入：head = [7,7,7,7], val = 7
 * 输出：[]
 * <p>
 * <p>
 * <p>
 * 提示：
 * <p>
 * 列表中的节点数目在范围 [0, 104] 内
 * 1 <= Node.val <= 50
 * 0 <= val <= 50
 */
public class Demo203 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 做题时间：10:24
     *
     * @param args
     */
    public static void main(String[] args) {

//        int len = 3;


        int[] nums = {6};
        ListNode head = new ListNode(nums[0]);
        ListNode temp = head;
        for (int i = 1; i < nums.length; i++) {
            temp.next = new ListNode(nums[i]);
            temp = temp.next;
        }

        ListNode newNode = removeElements(head, 6);
        System.out.println("Demo203.main");
    }

    public static ListNode removeElements(ListNode head, int val) {
        //先找到头
        while (head != null && head.val == val) {
            head = head.next;
        }
        ListNode newHead = head;
        while (head != null) {
            while (head.next != null && head.next.val == val) {
                head.next = head.next.next;
            }
            head = head.next;
        }
        return newHead;
    }

    public static ListNode removeElements1(ListNode head, int val) {
        ListNode listNode = new ListNode();
        ListNode newNode = listNode;
        while (head != null) {
            if (head.val != val) {
                newNode.next = head;
                newNode = newNode.next;
            } else {
                //结尾为删除结点
                newNode.next = null;
            }
            head = head.next;
        }
        return listNode.next;
    }
}
